package cn.telling.product.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.telling.common.util.TellingConstance;
import cn.telling.common.util.UserUtil;
import cn.telling.product.dao.IAreaInfoDao;
import cn.telling.product.dao.IDirectionalDao;
import cn.telling.product.dao.IStoreProductDao;
import cn.telling.product.dao.ISupplyDao;
import cn.telling.product.service.IStoreProductService;
import cn.telling.product.vo.AreaInfoVo;
import cn.telling.product.vo.LgStoreUpdate;
import cn.telling.product.vo.StoreProductVo;
import cn.telling.product.vo.SupplyArea0Vo;
import cn.telling.product.vo.SupplyVo;
import cn.telling.sellerCenter.vo.ProductMainVO;
import cn.telling.sellercentre.dao.IProductMainDao;
import cn.telling.utils.StringHelperTools;

/**
 * 
 * @ClassName: StoreProductServiceImpl 
 * @Description: 产品库存业务服务接口的实现
 * @author 陈赟 
 * @date 2015年6月17日 上午9:30:07 
 *
 */
@Service("storeProductService")
public class StoreProductServiceImpl implements IStoreProductService{
    
    private static final Logger LOGGER = LoggerFactory.getLogger(StoreProductServiceImpl.class);
    
    @Autowired
    @Qualifier("storeProductDao")
    private IStoreProductDao storeProductDao;
    
    @Autowired
    @Qualifier("directionalDao")
    private IDirectionalDao directionalDao;

    @Autowired
    @Qualifier("supplyDao")
    private ISupplyDao supplyDao;

    @Autowired
    @Qualifier("productMainDao")
    private IProductMainDao productMainDao;

    @Autowired
    @Qualifier("areaInfoDao")
    private IAreaInfoDao areaInfoDao;

    @Override
    @Transactional(value="txManager",isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
    public int storeProductLog(StoreProductVo vo) {
        if(vo == null) {
            return 0;
        }
        return storeProductDao.storeProductLog(vo);
    }

    @Override
    public void updateStoreProduct(String id, String allocatable) {
        storeProductDao.updateStoreProduct(id, allocatable);
    }

	@Override
	@Transactional(value="txManager",isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public boolean updateStockNumber(String orderCode, Map<String, BigDecimal> storeNum, boolean isAdd) {
	    LOGGER.debug("订单更新库存的参数：{orderCode={}, storeNum={}, isAdd={}}", new Object[]{orderCode, storeNum, isAdd});
	    // 先检查库存参数是否有值
	    if(storeNum == null || storeNum.isEmpty()) {
	        LOGGER.debug("订单更新库存：参数storeNum为空！");
	        return false;
	    } else {
	        // 检查库存是否合法，是否为负数
	        Iterator<Entry<String, BigDecimal>> it = storeNum.entrySet().iterator();
	        while(it.hasNext()) {
	            Entry<String, BigDecimal> entry = it.next();
	            String key = entry.getKey();
	            BigDecimal value = entry.getValue();
	            if(value == null) {
	                LOGGER.debug("订单更新库存：storeNum中，key为{}的值为空", key);
	                return false;
	            }
	            long num = value.longValue();
	            if(num < 0) {
	                LOGGER.debug("订单更新库存：storeNum中，key为{}的值小于0", num);
	                return false;
	            }
	        }
	        
            // 根据产品发布ID查出对应的可用库存
            StringBuilder supplyArea0Ids = new StringBuilder();
            List<String> productIdList = new ArrayList<String>();
            productIdList.addAll(storeNum.keySet());
            for(String productId : productIdList) {
                supplyArea0Ids.append(productId);
                supplyArea0Ids.append(",");
            }
            String ids = supplyArea0Ids.substring(0, supplyArea0Ids.length() - 1);
            List<SupplyArea0Vo> supplyArea0List = directionalDao.getSupplyArea0ByIds(ids);

            // 查询发布记录，看是否存在
            if(supplyArea0List == null || supplyArea0List.isEmpty()) {
                LOGGER.debug("订单更新库存失败：storeNum中，根据productId获取不到发布记录");
                return false;
            } else {
                List<SupplyArea0Vo> updatePublishList = new ArrayList<SupplyArea0Vo>();
                List<StoreProductVo> updateStoreList = new ArrayList<StoreProductVo>();
                List<LgStoreUpdate> lgStoreUpdateList = new ArrayList<LgStoreUpdate>();
    	        // 如果是减库存，则需要验证库存是否足够
    	        if(!isAdd) {
    	            it = storeNum.entrySet().iterator();
	                while(it.hasNext()) {
	                    Entry<String, BigDecimal> entry = it.next();
	                    String key = entry.getKey();
	                    long value = entry.getValue().longValue();
	                    for(SupplyArea0Vo vo : supplyArea0List) {
	                        if(vo.getDelflag().equals(TellingConstance.DEL_FLAG_0)) {
                                LOGGER.debug("订单更新库存失败：supplyarea0Id为{}已取消发布", new Object[]{key});
	                            return false;
	                        }
	                        
	                        long store = vo.getOverplusNumber().longValue();
	                        
	                        if(key.equals(vo.getId().toString())) {
	                            if(value > store) {
	                                LOGGER.debug("订单更新库存失败：productId为{}的库存不足，库存是{}，需要库存是{}", new Object[]{key, store, value});
	                                return false;
	                            } else {
	                                String saleType = vo.getSaleType();
                                    // 如果是非定向发布，则需要找出同批发布的记录，统一修改库存
	                                // 如果是非定向发布，则需要判断供应商类型是否为天联华建，如果是，则还需要修改store_product的库存
	                                if(saleType.equals(TellingConstance.SALETYPE2)) {
                                        String shopProductId = vo.getSupplyProductId().toString();
                                        //根据产品指定供应商ID查出对应的非定向发布记录
                                        List<SupplyArea0Vo> batchVo = directionalDao.getSupplyArea0ByShopProductId(shopProductId);
                                        if(batchVo == null || batchVo.isEmpty()) {
                                            LOGGER.debug("订单更新库存失败：所传发布ID是非定向发布，但没有找到发布有效的记录", new Object[]{key, store, value});
                                            return false;
                                        }
                                        for(SupplyArea0Vo bVo : batchVo) {
                                            // 减库存日志
                                            LgStoreUpdate lg = new LgStoreUpdate();
                                            lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
                                            lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
                                            lg.setUpdate_type(TellingConstance.TYPE_ORDER_OUT);
                                            lg.setUpdate_count(entry.getValue().negate());
                                            setPublishLog(orderCode, bVo, lg);
                                            lgStoreUpdateList.add(lg);
                                            
                                            // 减去库存，放入要修改库存的列表中
                                            bVo.setOverplusNumber(new BigDecimal(store - value));
                                            updatePublishList.add(bVo);
                                        }
                                        // 根据产品指定供应商ID查出供应商信息
                                        SupplyVo supplyVo = supplyDao.findSupplyByShopProductId(shopProductId);
	                                    if(supplyVo.getSupply_type().equals(UserUtil.TELLING_SUPPLY_17)) {
	                                        // 根据产品指定供应商ID查出产品信息
	                                        ProductMainVO productMainVo = productMainDao.getProductMainByShopProductId(shopProductId);
	                                        String areaId = vo.getAreaId().toString();
	                                        AreaInfoVo areainfo = areaInfoDao.getAreaInfoByAreaId(areaId);
	                                        if(areainfo.getAreaLevel().toString().equals("4")) {
	                                            areainfo = areaInfoDao.getAreaInfoByAreaId(areainfo.getParentId().toString());
	                                            areaId = areainfo.getParentId().toString();
	                                        } else if(areainfo.getAreaLevel().toString().equals("3")) {
	                                            areaId = areainfo.getParentId().toString();
	                                        }
	                                        StoreProductVo storeVo = storeProductDao.getStoreProductByAreaIdAndProductId(areaId, productMainVo.getProductId().toString());
	                                        if(storeVo != null) {
	                                            long allocatable = storeVo.getAllocatable().longValue();
	                                            if(value > allocatable) {
	                                                LOGGER.debug("订单更新库存失败：productId为{}的store_product库存不足，库存是{}，需要库存是{}", new Object[]{key, allocatable, value});
	                                                return false;
	                                            } else {
                                                    // 减库存日志
	                                                LgStoreUpdate lg = new LgStoreUpdate();
                                                    lg = new LgStoreUpdate();
                                                    lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
                                                    lg.setUpdate_target(TellingConstance.TARGET_STORE);
                                                    lg.setUpdate_type(TellingConstance.TYPE_ORDER_OUT);
                                                    lg.setUpdate_count(entry.getValue().negate());
                                                    setStoreLog(orderCode, lg, storeVo);
                                                    lgStoreUpdateList.add(lg);
                                                    
    	                                            storeVo.setAllocatable(new BigDecimal(allocatable - value));
    	                                            updateStoreList.add(storeVo);
	                                            }
	                                        }
	                                    }
	                                } else {
	                                	String isShare = vo.getIsShare();
	                                	LOGGER.debug(String.format("[%s]是否共享[%s]", vo.getId(),vo.getIsShare()));
	                                	if(!"".equals(StringHelperTools.nvl(isShare))){
	                                		String shareCode = vo.getShareCode();
	                                		LOGGER.debug(String.format("[%s]共享编码[%s]", vo.getId(),vo.getShareCode()));
	                                		//根据shareCode查询出所有符合的列表
	                                		List<SupplyArea0Vo> supplyArea0VoList = directionalDao.getSupplyArea0ByShareCode(shareCode);
	                                		
	                                		if(supplyArea0VoList != null){
	                                			for(SupplyArea0Vo supplyArea0Vo : supplyArea0VoList){
	                                                // 减库存日志
	                                                LgStoreUpdate lg = new LgStoreUpdate();
	                                                lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
	                                                lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
	                                                lg.setUpdate_type(TellingConstance.TYPE_ORDER_OUT);
	                                                lg.setUpdate_count(entry.getValue().negate());
	                                                setPublishLog(orderCode, vo, lg);
	                                                lgStoreUpdateList.add(lg);
	                                                
	                                				supplyArea0Vo.setOverplusNumber(new BigDecimal(store - value));
	                                				updatePublishList.add(supplyArea0Vo);
	                                			}
	                                		}
	                                		
	                                	}else{
	                                        // 减库存日志
	                                        LgStoreUpdate lg = new LgStoreUpdate();
	                                        lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
	                                        lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
	                                        lg.setUpdate_type(TellingConstance.TYPE_ORDER_OUT);
	                                        lg.setUpdate_count(entry.getValue().negate());
	                                        setPublishLog(orderCode, vo, lg);
	                                        lgStoreUpdateList.add(lg);
	                                        
		                                    // 减去库存，放入要修改库存的列表中
		                                    vo.setOverplusNumber(new BigDecimal(store - value));
		                                    updatePublishList.add(vo);
	                                	}
	                                }
	                            }
	                        }
	                    }
	                }
    	        } else {
    	            it = storeNum.entrySet().iterator();
    	            while(it.hasNext()) {
                        Entry<String, BigDecimal> entry = it.next();
                        String key = entry.getKey();
                        long value = entry.getValue().longValue();
                        for(SupplyArea0Vo vo : supplyArea0List) {
                            long store = vo.getOverplusNumber().longValue();
                            if(key.equals(vo.getId().toString())) {                                
                                String saleType = vo.getSaleType();
                                String shopProductId = vo.getSupplyProductId().toString();
                                // 根据产品指定供应商ID查出供应商信息
                                SupplyVo supplyVo = supplyDao.findSupplyByShopProductId(shopProductId);
                                // 如果是非定向发布，则需要找出同批发布的记录，统一修改库存
                                // 如果是非定向发布，则需要判断供应商类型是否为天联华建，如果是，则还需要修改store_product的库存
                                if(saleType.equals(TellingConstance.SALETYPE2)) {
                                    //根据产品指定供应商ID查出对应的非定向发布记录
                                    List<SupplyArea0Vo> batchVo = directionalDao.getSupplyArea0ByShopProductId(shopProductId);
                                    for(SupplyArea0Vo bVo : batchVo) {
                                        // 加库存日志
                                        LgStoreUpdate lg = new LgStoreUpdate();
                                        lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
                                        lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
                                        lg.setUpdate_type(TellingConstance.TYPE_ORDER_IN);
                                        lg.setUpdate_count(entry.getValue());
                                        setPublishLog(orderCode, bVo, lg);
                                        lgStoreUpdateList.add(lg);
                                        
                                        // 加库存，放入要修改库存的列表中
                                        bVo.setOverplusNumber(new BigDecimal(store + value));
                                        updatePublishList.add(bVo);
                                    }
                                    if(supplyVo.getSupply_type().equals(UserUtil.TELLING_SUPPLY_17)) {
                                        // 根据产品指定供应商ID查出产品信息
                                        ProductMainVO productMainVo = productMainDao.getProductMainByShopProductId(shopProductId);
                                        String areaId = vo.getAreaId().toString();
                                        AreaInfoVo areainfo = areaInfoDao.getAreaInfoByAreaId(areaId);
                                        if(areainfo.getAreaLevel().toString().equals("4")) {
                                            areainfo = areaInfoDao.getAreaInfoByAreaId(areainfo.getParentId().toString());
                                            areaId = areainfo.getParentId().toString();
                                        } else if(areainfo.getAreaLevel().toString().equals("3")) {
                                            areaId = areainfo.getParentId().toString();
                                        }
                                        StoreProductVo storeVo = storeProductDao.getStoreProductByAreaIdAndProductId(areaId, productMainVo.getProductId().toString());
                                        if(storeVo != null) {
                                            // 加库存日志
                                            LgStoreUpdate lg = new LgStoreUpdate();
                                            lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
                                            lg.setUpdate_target(TellingConstance.TARGET_STORE);
                                            lg.setUpdate_type(TellingConstance.TYPE_ORDER_IN);
                                            lg.setUpdate_count(entry.getValue());
                                            setStoreLog(orderCode, lg, storeVo);
                                            lgStoreUpdateList.add(lg);
                                            
                                            long allocatable = storeVo.getAllocatable().longValue();
                                            storeVo.setAllocatable(new BigDecimal(allocatable + value));
                                            updateStoreList.add(storeVo);
                                            
                                        }
                                    }
                                } else {
                                	
                                	String isShare = vo.getIsShare();
                                	LOGGER.debug(String.format("[%s]是否共享[%s]", vo.getId(),vo.getIsShare()));
                                	if(!"".equals(StringHelperTools.nvl(isShare))){
                                		String shareCode = vo.getShareCode();
                                		LOGGER.debug(String.format("[%s]共享编码[%s]", vo.getId(),vo.getShareCode()));
                                		//根据shareCode查询出所有符合的列表
                                		List<SupplyArea0Vo> supplyArea0VoList = directionalDao.getSupplyArea0ByShareCode(shareCode);
                                		
                                		if(supplyArea0VoList != null){
                                			for(SupplyArea0Vo supplyArea0Vo : supplyArea0VoList){
                                                // 加库存日志
                                                LgStoreUpdate lg = new LgStoreUpdate();
                                                lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
                                                lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
                                                lg.setUpdate_type(TellingConstance.TYPE_ORDER_IN);
                                                lg.setUpdate_count(entry.getValue());
                                                setPublishLog(orderCode, vo, lg);
                                                lgStoreUpdateList.add(lg);
                                                
                                				supplyArea0Vo.setOverplusNumber(new BigDecimal(store + value));
                                				updatePublishList.add(supplyArea0Vo);
                                			}
                                		}
                                		
                                	}else{
                                        // 加库存日志
                                        LgStoreUpdate lg = new LgStoreUpdate();
                                        lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
                                        lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
                                        lg.setUpdate_type(TellingConstance.TYPE_ORDER_IN);
                                        lg.setUpdate_count(entry.getValue());
                                        setPublishLog(orderCode, vo, lg);
                                        lgStoreUpdateList.add(lg);
                                        
	                                    // 加库存，放入要修改库存的列表中
	                                    vo.setOverplusNumber(new BigDecimal(store + value));
	                                    updatePublishList.add(vo);
                                	}
                                	
                                	// 如果是加库存，则需要判断发布是否已取消，若已取消还得将库存还给store_product 并且是天联华建供应商
                                	if(vo.getDelflag().equals(TellingConstance.DEL_FLAG_0) && supplyVo.getSupply_type().equals(UserUtil.TELLING_SUPPLY_17)) {
                                	    // 根据产品指定供应商ID查出产品信息
                                        ProductMainVO productMainVo = productMainDao.getProductMainByShopProductId(shopProductId);
                                        String areaId = vo.getAreaId().toString();
                                        AreaInfoVo areainfo = areaInfoDao.getAreaInfoByAreaId(areaId);
                                        if(areainfo.getAreaLevel().toString().equals("4")) {
                                            areainfo = areaInfoDao.getAreaInfoByAreaId(areainfo.getParentId().toString());
                                            areaId = areainfo.getParentId().toString();
                                        } else if(areainfo.getAreaLevel().toString().equals("3")) {
                                            areaId = areainfo.getParentId().toString();
                                        }
                                        StoreProductVo storeVo = storeProductDao.getStoreProductByAreaIdAndProductId(areaId, productMainVo.getProductId().toString());
                                        if(storeVo != null) {
                                            // 加库存日志
                                            LgStoreUpdate lg = new LgStoreUpdate();
                                            lg.setUpdate_source(TellingConstance.SOURCE_ORDER);
                                            lg.setUpdate_target(TellingConstance.TARGET_STORE);
                                            lg.setUpdate_type(TellingConstance.TYPE_ORDER_IN);
                                            lg.setUpdate_count(entry.getValue());
                                            setStoreLog(orderCode, lg, storeVo);
                                            lgStoreUpdateList.add(lg);
                                            
                                            long allocatable = storeVo.getAllocatable().longValue();
                                            storeVo.setAllocatable(new BigDecimal(allocatable + value));
                                            updateStoreList.add(storeVo);
                                            
                                        }
                                	}
                                   
                                }
                            }
                        }
                    }
    	        }
                // 更新库存
                int updateNum = storeProductDao.updateStoreProductBatch(updatePublishList, updateStoreList, TellingConstance.SOURCE_ORDER);
                LOGGER.debug("00000000扣减库存返回值:" + updateNum);
                // 保存修改库存的日志
                int logNum = storeProductDao.insertLgStoreUpdate(lgStoreUpdateList);
                LOGGER.debug("00000000更新日志返回值:" + logNum);
                //2015-07-06 修改扣减库存成功就可以返回true liugeng
                if(updateNum > 0 ) {
                    return true;
                }
            }
	    }
		return false;
	}
	
	

    private void setPublishLog(String orderCode, SupplyArea0Vo vo, LgStoreUpdate lg) {
        lg.setSource_code(orderCode);
        lg.setTarget_code(vo.getId().toString());
        lg.setProduct_id(vo.getProductId());
        lg.setBefore_update_stock(vo.getStockNumber());
        lg.setBefore_update_available(vo.getOverplusNumber());
    }

    private void setStoreLog(String sourceCode, LgStoreUpdate lg, StoreProductVo storeVo) {
        lg.setSource_code(sourceCode);
        lg.setTarget_code(storeVo.getPk_stordoc());
        lg.setProduct_id(storeVo.getProductid());
        lg.setBefore_update_stock(storeVo.getQuantity());
        lg.setBefore_update_available(storeVo.getAllocatable());
    }

    @Override
    @Transactional(value="txManager",isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
    public boolean updatePkStockNumber(String allocateCode, String pkStorDoc, Map<BigDecimal, BigDecimal> storeNum, boolean isAdd) {
        LOGGER.debug("仓库调拨更新库存的参数：{allocateCode={}, pkStorDoc={}, storeNum={}, isAdd={}}", new Object[]{allocateCode, pkStorDoc, storeNum, isAdd});
        // 先检查库存参数是否有值
        if(storeNum == null || storeNum.isEmpty()) {
            LOGGER.debug("调拨更新库存：参数storeNum为空！");
            return false;
        } else {
            // 检查库存是否合法，是否为负数
            Iterator<Entry<BigDecimal, BigDecimal>> it = storeNum.entrySet().iterator();
            while(it.hasNext()) {
                Entry<BigDecimal, BigDecimal> entry = it.next();
                BigDecimal key = entry.getKey();
                BigDecimal value = entry.getValue();
                if(value == null) {
                    LOGGER.debug("调拨更新库存：storeNum中，key为{}的值为空", key);
                    return false;
                }
                long num = value.longValue();
                if(num < 0) {
                    LOGGER.debug("调拨更新库存：storeNum中，key为{}的值小于0", num);
                    return false;
                }
            }
            
            // 根据产品发布ID查出对应的可用库存，先拼出产品ID串
            StringBuilder productIds = new StringBuilder();
            List<BigDecimal> productIdList = new ArrayList<BigDecimal>();
            productIdList.addAll(storeNum.keySet());
            for(BigDecimal productId : productIdList) {
                productIds.append(productId.toString());
                productIds.append(",");
            }
            String ids = productIds.substring(0, productIds.length() - 1);
            
            
            // 根据产品ID和仓库编码查询库存信息
            List<StoreProductVo> storeProductList = storeProductDao.getStoreProductByPkStorDocAndProductIds(pkStorDoc, ids);
            
            List<LgStoreUpdate> lgStoreUpdateList = new ArrayList<LgStoreUpdate>();
            // 如果这些产品都不存在库存记录
            if(storeProductList == null || storeProductList.isEmpty()) {
                // 调入
                if(isAdd) {
                    List<StoreProductVo> insertStoreList = new ArrayList<StoreProductVo>();
                    it = storeNum.entrySet().iterator();
                    while(it.hasNext()) {
                        Entry<BigDecimal, BigDecimal> entry = it.next();
                        BigDecimal key = entry.getKey();
                        BigDecimal value = entry.getValue();
                        
                        StoreProductVo storeProductVo = new StoreProductVo();
                        storeProductVo.setPk_stordoc(pkStorDoc);
                        storeProductVo.setProductid(key);
                        storeProductVo.setQuantity(new BigDecimal(0)); // 无库存，则初始值为0
                        storeProductVo.setAllocatable(new BigDecimal(0)); // 无库存，则初始值为0
                        
                        // 加库存日志
                        LgStoreUpdate lg = new LgStoreUpdate();
                        lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                        lg.setUpdate_target(TellingConstance.TARGET_STORE);
                        lg.setUpdate_type(TellingConstance.TYPE_STORE_IN);
                        lg.setUpdate_count(entry.getValue());
                        setStoreLog(allocateCode, lg, storeProductVo);
                        lgStoreUpdateList.add(lg);
                        
                        storeProductVo.setQuantity(value);
                        storeProductVo.setAllocatable(value);
                        
                        insertStoreList.add(storeProductVo);
                    }
                    storeProductDao.insertStoreProduct(insertStoreList);
                    LOGGER.debug("仓库调拨入库没有找到对应的库存信息，调入成功，新增{}条库存信息：调拨单号为{}，仓库编码为{}，产品ID为{}", new Object[]{insertStoreList.size(), allocateCode, pkStorDoc, ids});
                    return true;
                } else {
                    LOGGER.debug("仓库调拨出库没有找到对应的库存信息，调出失败：调拨单号为{}，仓库编码为{}，产品ID为{}", new Object[]{allocateCode, pkStorDoc, ids});
                    return false;
                }
            } else if(storeProductList.size() == productIdList.size()) { // 如果全部存在，则直接修改库存数量
                // 更新产品库存的信息
                for(StoreProductVo storeProductVo : storeProductList) {
                    BigDecimal productId = storeProductVo.getProductid();
                    long num = storeNum.get(productId).longValue();
                    
                    long allocatable = storeProductVo.getAllocatable().longValue();
                    long quantity = storeProductVo.getQuantity().longValue();
                    
                    if(isAdd) { // 调入
                        // 加库存日志
                        LgStoreUpdate lg = new LgStoreUpdate();
                        lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                        lg.setUpdate_target(TellingConstance.TARGET_STORE);
                        lg.setUpdate_type(TellingConstance.TYPE_STORE_IN);
                        lg.setUpdate_count(new BigDecimal(num));
                        setStoreLog(allocateCode, lg, storeProductVo);
                        lgStoreUpdateList.add(lg);
                        
                        allocatable += num;
                        quantity += num;
                    } else { // 调出
                        // 减库存日志
                        LgStoreUpdate lg = new LgStoreUpdate();
                        lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                        lg.setUpdate_target(TellingConstance.TARGET_STORE);
                        lg.setUpdate_type(TellingConstance.TYPE_STORE_OUT);
                        lg.setUpdate_count(new BigDecimal(num).negate());
                        setStoreLog(allocateCode, lg, storeProductVo);
                        lgStoreUpdateList.add(lg);
                        
                        allocatable -= num;
                        quantity -= num;
                        if(allocatable < 0) {
                            LOGGER.debug("调拨更新库存失败：产品ID为{}，仓库为{}的发布的可用库存不足，可用库存是{}，需要调出的库存是{}", new Object[]{productId, pkStorDoc, allocatable, num});
                            return false;
                        }
                    }
                    storeProductVo.setAllocatable(new BigDecimal(allocatable));
                    storeProductVo.setQuantity(new BigDecimal(quantity));
                }
                
                // 更新天联华建非定向发布的库存信息
                // 根据产品ID、仓库编码查出天联华建非定向发布的记录
                List<SupplyArea0Vo> supplyArea0List = storeProductDao.getSupplyArea0ByPkStorDocAndProductIds(pkStorDoc, ids);
                // 如果查出的有结果，则还需要修改发布记录中的库存
                if(supplyArea0List != null && supplyArea0List.size() > 0) {
                    // 调入
                    if(isAdd) {
                        for(SupplyArea0Vo vo : supplyArea0List) {
                            long num = storeNum.get(vo.getProductId()).longValue();
                            
                            // 加库存日志
                            LgStoreUpdate lg = new LgStoreUpdate();
                            lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                            lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
                            lg.setUpdate_type(TellingConstance.TYPE_STORE_IN);
                            lg.setUpdate_count(new BigDecimal(num));
                            setPublishLog(allocateCode, vo, lg);
                            lgStoreUpdateList.add(lg);
                            
                            long stockNumber = vo.getStockNumber().longValue() + num;
                            long overplusNumber = vo.getOverplusNumber().longValue() + num;
                            vo.setStockNumber(new BigDecimal(stockNumber));
                            vo.setOverplusNumber(new BigDecimal(overplusNumber));
                        }
                    } else { // 调出
                        for(SupplyArea0Vo vo : supplyArea0List) {
                            long num = storeNum.get(vo.getProductId()).longValue();
                            
                            // 减库存日志
                            LgStoreUpdate lg = new LgStoreUpdate();
                            lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                            lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
                            lg.setUpdate_type(TellingConstance.TYPE_STORE_OUT);
                            lg.setUpdate_count(new BigDecimal(num).negate());
                            setPublishLog(allocateCode, vo, lg);
                            lgStoreUpdateList.add(lg);
                            
                            long stockNumber = vo.getStockNumber().longValue() - num;
                            long overplusNumber = vo.getOverplusNumber().longValue() - num;
                            if(overplusNumber < 0) {
                                LOGGER.debug("调拨更新库存失败：产品ID为{}，仓库为{}的发布的可用库存不足，可用库存是{}，需要调出的库存是{}", new Object[]{ids, pkStorDoc, vo.getOverplusNumber().longValue(), num});
                                return false;
                            }
                            vo.setStockNumber(new BigDecimal(stockNumber));
                            vo.setOverplusNumber(new BigDecimal(overplusNumber));
                        }
                    }
                }
                
                // 更新库存
                int updateNum = storeProductDao.updateStoreProductBatch(supplyArea0List, storeProductList, TellingConstance.SOURCE_ALLOCATE);
                // 保存修改库存的日志
                int logNum = storeProductDao.insertLgStoreUpdate(lgStoreUpdateList);
                LOGGER.debug("00000000更新日志返回值:" + logNum);
                if(updateNum > 0) {
                    return true;
                }
            } else { // 如果是有一部分产品没有库存信息，则新增不存在的库存，修改已存在的库存
                // 列出存在库存的产品
                List<BigDecimal> existList = new ArrayList<BigDecimal>();
                for(StoreProductVo storeProductVo : storeProductList) {
                    existList.add(storeProductVo.getProductid());
                }
                // 查出不存在库存的产品
                List<BigDecimal> notExistList = new ArrayList<BigDecimal>();
                notExistList.addAll(productIdList);
                notExistList.removeAll(existList);
                
                // 调入
                if(isAdd) {
                    // 插和不存在的库存
                    List<StoreProductVo> insertStoreList = new ArrayList<StoreProductVo>();
                    for(BigDecimal productId : notExistList) {
                        BigDecimal value = storeNum.get(productId);
                        
                        StoreProductVo storeProductVo = new StoreProductVo();
                        storeProductVo.setPk_stordoc(pkStorDoc);
                        storeProductVo.setProductid(productId);
                        storeProductVo.setQuantity(new BigDecimal(0)); // 无库存，则初始值为0
                        storeProductVo.setAllocatable(new BigDecimal(0)); // 无库存，则初始值为0
                        
                        // 加库存日志
                        LgStoreUpdate lg = new LgStoreUpdate();
                        lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                        lg.setUpdate_target(TellingConstance.TARGET_STORE);
                        lg.setUpdate_type(TellingConstance.TYPE_STORE_IN);
                        lg.setUpdate_count(value);
                        setStoreLog(allocateCode, lg, storeProductVo);
                        lgStoreUpdateList.add(lg);
                        
                        storeProductVo.setQuantity(value);
                        storeProductVo.setAllocatable(value);
                        
                        insertStoreList.add(storeProductVo);
                    }
                    // 修改存在的库存 
                    for(StoreProductVo storeProductVo : storeProductList) {
                        BigDecimal productId = storeProductVo.getProductid();
                        long num = storeNum.get(productId).longValue();

                        // 加库存日志
                        LgStoreUpdate lg = new LgStoreUpdate();
                        lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                        lg.setUpdate_target(TellingConstance.TARGET_STORE);
                        lg.setUpdate_type(TellingConstance.TYPE_STORE_IN);
                        lg.setUpdate_count(new BigDecimal(num));
                        setStoreLog(allocateCode, lg, storeProductVo);
                        lgStoreUpdateList.add(lg);
                        
                        long allocatable = storeProductVo.getAllocatable().longValue();
                        long quantity = storeProductVo.getQuantity().longValue();
                        
                        allocatable += num;
                        quantity += num;
                            
                        storeProductVo.setAllocatable(new BigDecimal(allocatable));
                        storeProductVo.setQuantity(new BigDecimal(quantity));
                    }
                    // 更新天联华建非定向发布的库存信息
                    // 根据产品ID、仓库编码查出天联华建非定向发布的记录
                    List<SupplyArea0Vo> supplyArea0List = storeProductDao.getSupplyArea0ByPkStorDocAndProductIds(pkStorDoc, ids);
                    // 如果查出的有结果，则还需要修改发布记录中的库存
                    if(supplyArea0List != null && supplyArea0List.size() > 0) {
                        for(SupplyArea0Vo vo : supplyArea0List) {
                            long num = storeNum.get(vo.getProductId()).longValue();
                            
                            // 加库存日志
                            LgStoreUpdate lg = new LgStoreUpdate();
                            lg.setUpdate_source(TellingConstance.SOURCE_ALLOCATE);
                            lg.setUpdate_target(TellingConstance.TARGET_PUBLISH);
                            lg.setUpdate_type(TellingConstance.TYPE_STORE_IN);
                            lg.setUpdate_count(new BigDecimal(num));
                            setPublishLog(allocateCode, vo, lg);
                            lgStoreUpdateList.add(lg);
                            
                            long stockNumber = vo.getStockNumber().longValue() + num;
                            long overplusNumber = vo.getOverplusNumber().longValue() + num;
                            vo.setStockNumber(new BigDecimal(stockNumber));
                            vo.setOverplusNumber(new BigDecimal(overplusNumber));
                        }
                    }

                    storeProductDao.insertStoreProduct(insertStoreList);
                    LOGGER.debug("仓库调拨入库没有找到对应的库存信息，调入成功，新增{}条库存信息：调拨单号为{}，仓库编码为{}，产品ID为{}", new Object[]{insertStoreList.size(), allocateCode, pkStorDoc, ids});
                    // 更新库存
                    int updateNum = storeProductDao.updateStoreProductBatch(supplyArea0List, storeProductList, TellingConstance.SOURCE_ALLOCATE);
                    // 保存修改库存的日志
                    int logNum = storeProductDao.insertLgStoreUpdate(lgStoreUpdateList);
                    LOGGER.debug("00000000更新日志返回值:" + logNum);
                    if(updateNum > 0) {
                        return true;
                    }
                } else {
                    LOGGER.debug("仓库调拨出库没有找到对应的库存信息，调出失败：调拨单号为{}，仓库编码为{}，产品ID为{}", new Object[]{allocateCode, pkStorDoc, ids});
                    return false;
                }
            }
        }
        return false;
    }

}
